// 音效管理工具

export enum SoundType {
  SUCCESS = 'success',
  ERROR = 'error',
  CLICK = 'click',
  DRAG = 'drag',
  DROP = 'drop',
  UNLOCK = 'unlock',
  BADGE = 'badge'
}

class SoundManager {
  private sounds: Map<SoundType, HTMLAudioElement> = new Map()
  private enabled: boolean = true

  constructor() {
    // 这里可以预加载音效文件
    // 由于我们没有实际的音频文件，使用 Web Audio API 生成简单的音效
  }

  // 播放成功音效
  playSuccess() {
    if (!this.enabled) return
    this.playTone(523.25, 0.2) // C5
    setTimeout(() => this.playTone(659.25, 0.2), 100) // E5
    setTimeout(() => this.playTone(783.99, 0.3), 200) // G5
  }

  // 播放错误音效（温柔的提示）
  playError() {
    if (!this.enabled) return
    this.playTone(392, 0.15) // G4
    setTimeout(() => this.playTone(349.23, 0.2), 100) // F4
  }

  // 播放点击音效
  playClick() {
    if (!this.enabled) return
    this.playTone(440, 0.05) // A4
  }

  // 播放拖拽音效
  playDrag() {
    if (!this.enabled) return
    this.playTone(523.25, 0.05) // C5
  }

  // 播放放置音效
  playDrop() {
    if (!this.enabled) return
    this.playTone(659.25, 0.1) // E5
  }

  // 播放解锁音效
  playUnlock() {
    if (!this.enabled) return
    this.playTone(523.25, 0.1)
    setTimeout(() => this.playTone(659.25, 0.1), 80)
    setTimeout(() => this.playTone(783.99, 0.1), 160)
    setTimeout(() => this.playTone(1046.5, 0.2), 240) // C6
  }

  // 播放获得徽章音效
  playBadge() {
    if (!this.enabled) return
    this.playTone(523.25, 0.1)
    setTimeout(() => this.playTone(659.25, 0.1), 100)
    setTimeout(() => this.playTone(783.99, 0.1), 200)
    setTimeout(() => this.playTone(1046.5, 0.1), 300)
    setTimeout(() => this.playTone(1318.51, 0.3), 400) // E6
  }

  // 使用 Web Audio API 生成音调
  private playTone(frequency: number, duration: number) {
    try {
      const audioContext = new (window.AudioContext || (window as any).webkitAudioContext)()
      const oscillator = audioContext.createOscillator()
      const gainNode = audioContext.createGain()

      oscillator.connect(gainNode)
      gainNode.connect(audioContext.destination)

      oscillator.frequency.value = frequency
      oscillator.type = 'sine'

      gainNode.gain.setValueAtTime(0.3, audioContext.currentTime)
      gainNode.gain.exponentialRampToValueAtTime(0.01, audioContext.currentTime + duration)

      oscillator.start(audioContext.currentTime)
      oscillator.stop(audioContext.currentTime + duration)
    } catch (e) {
      console.warn('音效播放失败:', e)
    }
  }

  // 启用/禁用音效
  setEnabled(enabled: boolean) {
    this.enabled = enabled
  }

  isEnabled() {
    return this.enabled
  }
}

export const soundManager = new SoundManager()
